package io.shallwe._admin.basedata.material;

import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import io.shallwe.common.model.MaterialNoName;

/**
 * 物料名称对照表Service
 * @author : 王小伟
 * @date : 2019-07-28 12:04:25
 */
public class MaterialNoNameService {

    private MaterialNoName dao = MaterialNoName.dao;

    public MaterialNoName findById(Integer id) {
        return dao.findById(id);
    }

    /**
     * 分页
     * @param offset
     * @param pageSize
     * @param materialCode
     * @param remark
     * @return
     */
    public Ret paginate(Integer offset, Integer pageSize, String materialCode, String remark) {
        int pageNumber=offset/pageSize+1;
        Kv condition =Kv.by("materialCode", materialCode).set("remark",remark);
        Page<Record> paginate = Db.template("material.paginate",condition).paginate(pageNumber, pageSize);
        return Ret.ok("total", paginate.getTotalRow()).set("rows", paginate.getList());
    }

    public Ret save(MaterialNoName codeName) {
        if(isMaterialCodeExist(codeName.getMaterialNo(),-1)){
            return Ret.fail("msg","物料编码已存在！");
        }
        if(codeName.save()) {
            return Ret.ok("msg", "操作成功！");
        }else{
            return Ret.ok("msg", "操作失败！");
        }
    }

    public Ret update(MaterialNoName codeName) {
        if(isMaterialCodeExist(codeName.getMaterialNo(),codeName.getId())){
            return Ret.fail("msg","物料编码已存在！");
        }
        if(codeName.update()) {
            return Ret.ok("msg", "操作成功！");
        }else{
            return Ret.ok("msg", "操作失败！");
        }
    }


    public Ret delete(String id) {
        if( dao.deleteById(id)) {
            return Ret.ok("msg", "操作成功！");
        }else{
            return Ret.ok("msg", "操作失败！");
        }
    }

    /**
     * 物料编码是否存在
     * @param materialCode
     * @param id
     * @return
     */
    public boolean isMaterialCodeExist(String materialCode ,Integer id){
        String sql="select id from t_material_no_name where material_no = ? and id != ?";
        return  Db.queryInt(sql,materialCode,id)!=null;
    }
}
